package com.ruoyi.yipaiju.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.CurrencyUtil;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.yipaiju.domain.WechatShare;
import com.ruoyi.yipaiju.service.IWechatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/wechat")
public class WechatController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(WechatController.class);

    @Autowired
    private IWechatService wechatService;
    @Autowired
    private ISysConfigService configService;

    /**
     * 小程序分享二维码
     * @param wechatShare
     * @return
     */
    @PostMapping("/getwxacodeunlimit")
    public ApiResult getwxacodeunlimit(@RequestBody WechatShare wechatShare)
    {
        try {
//            JSONObject jsonParams = JSONObject.parseObject(wechatShare.getParams());
            Map json = JSONObject.parse(wechatShare.getParams());

            // 生成二维码
            String secret = configService.selectConfigByKey("biz.wechat.xcx.secret");
            String access_token = wechatService.getAccessToken(wechatShare.getAppid(), secret);
            String base64 = wechatService.getwxacodeunlimit(access_token, wechatShare.getPath(), CurrencyUtil.mapToStr(json));
            return ApiResult.success("操作成功", base64);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ApiResult.error();
    }

    @PostMapping("/test")
    public ApiResult test(@RequestBody String body)
    {
        System.out.println(body);
        log.info("===============wechat test ===" + body);

        return ApiResult.success();
    }


//    提交验证使用
//    @Anonymous
//    @GetMapping("/subscribe")
//    public String subscribe(String signature, String timestamp, String nonce, String echostr)
//    {
//        logger.info("wechat validate  signature=" + signature + ",timestamp="+timestamp+ ",nonce="+nonce+ ",echostr="+echostr);
//
//        return echostr;
//    }

    @Anonymous
    @PostMapping("/subscribe")
    public String subscribe(@RequestBody String body)
    {
        logger.info("wechat push msg = " + body);




        return "success";
    }


}
